from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.views.decorators.csrf import csrf_protect
from django.views.decorators.cache import never_cache

from blog.forms import LoginForm
from blog.config import LOGIN_REDIRECT_URL, LOGOUT_URL

@never_cache
@csrf_protect
def login_user(request, next = LOGIN_REDIRECT_URL):
    if request.user.is_authenticated():
        return redirect(next)

    form = LoginForm()
    if request.POST.get('action', False) == 'login':
        user = authenticate(
            username = request.POST.get('username'),
            password = request.POST.get('password'),
        )
        # If user exists
        if user is not None and user.is_active:
            login(request, user)
            return redirect(next)
        # If user does not exist or password is wrong
        else:
            form = LoginForm(request.POST)
            messages.error(request, 'Your account does not exist or your password is wrong.')

    return render_to_response(
        'blog/login.html',
        {'form' : form},
        RequestContext(request),
    )

def logout_user(request, next = LOGOUT_URL):
    logout(request)
    return redirect(LOGOUT_URL)